import React, { useState, useRef, useEffect } from 'react';
import './Post.css'; // 样式
import { ReactComponent as Love } from '../assets/icons/Love.svg';
import { ReactComponent as Comment } from '../assets/icons/Comment.svg';
import { ReactComponent as Collect } from '../assets/icons/Collect.svg';
import Loved from '../assets/icons/Loved.png'; 
import Commenting from '../assets/icons/Commenting.png'; 
import Collected from '../assets/icons/Collected.png'; 
import { ReactComponent as FollowIcon } from '../assets/icons/Follow.svg'; // 关注图标
import { ReactComponent as FollowedIcon } from '../assets/icons/Followed.svg'; // 已关注图标
import { ReactComponent as SendIcon } from '../assets/icons/Send.svg'; // 发送评论图标
import { ReactComponent as DetailIcon} from '../assets/icons/details.svg'; //详情图标
import CommentItem from './CommentItem';
import { useNavigate } from 'react-router-dom';
import defaultAvatar from '../assets/images/默认头像.jpg';
import { collect, uncollect, like, unlike,follow, unfollow,getCommentsByBlogId, addComment } from '../api/userApi'; // 调整路径


const Post = ({  post, isDetailPage = false }) => {
  const [isFollowed, setIsFollowed] = useState(post.isFollowed);
  const [isLiked, setIsLiked] = useState(post.isLiked); // 初始状态
  const [isCommentedState, setIsCommentedState] = useState(isDetailPage); // 默认在详情页面时已打开
  const [isCollected, setIsCollected] = useState(post.isCollected);
  const [likesCount, setLikesCount] = useState(post.likeCount); // 使用状态管理点赞数
  const [commentsCount, setCommentsCount] = useState(post.commentCount); // 使用状态管理评论数
  const [commentText, setCommentText] = useState('');
  const [comments, setComments] = useState([]);
  const [commentStates, setCommentStates] = useState({});
  const [isCommentInputActive, setIsCommentInputActive] = useState(false);
  const [userId, setUserId] = useState(localStorage.getItem('userId')); // 获取当前用户 ID
  const followerId = localStorage.getItem('userId'); // 从 localStorage 获取当前用户 ID
  const [replyTo, setReplyTo] = useState(null);
  const [repliedId, setRepliedId] = useState(null);
  const sendIconRef = useRef(null);
  const commentInputRef = useRef(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // console.log("Current User ID:", userId);
  // console.log("Post User ID:", post.userId);
  // console.log('Interest ID:', post.interestId);



  // 格式化时间
  const formatDate = (dateString) => {
    const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false };
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', options).replace(/\//g, '-'); // 将 / 替换为 - 以符合中文日期格式
  };

  // 获取用户 ID
  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    }
  }, []);

  // 获取评论列表
  useEffect(() => {
    const fetchComments = async () => {
      try {
        const fetchedComments = await getCommentsByBlogId(post.blogId);
        setComments(fetchedComments);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchComments();
  }, [post.blogId]);



  // 切换关注状态函数
  const toggleFollow = async () => {
    if (isFollowed) {
        const response = await unfollow(followerId, post.userId); // 取消关注
        if (response.success) {
            setIsFollowed(false);
            //window.location.reload();
        } else {
            console.error(response.error);
        }
    } else {
        const response = await follow(followerId, post.userId); // 执行关注
        if (response.success) {
            setIsFollowed(true);
        } else {
            console.error(response.error);
        }
    }
  };

  // 切换点赞状态函数
  const toggleLike = async () => {
    if (isLiked) {
      const response = await unlike(userId, post.blogId); // 取消点赞
      if (response.success) {
        setIsLiked(false);
        setLikesCount((prevCount) => prevCount - 1); // 更新点赞数量
      } else {
        console.error(response.error);
      }
    } else {
      const response = await like(userId, post.blogId); // 执行点赞
      if (response.success) {
        setIsLiked(true);
        setLikesCount((prevCount) => prevCount + 1); // 更新点赞数量
      } else {
        console.error(response.error);
      }
    }
  };

  // 切换评论展开状态
  const toggleComment = () => {
    setIsCommentedState(!isCommentedState);
  };

  // 切换收藏状态
  const toggleCollect = async () => {
    if (isCollected) {
      const response = await uncollect(userId, post.interestId); // 取消收藏
      if (response.success) {
        setIsCollected(false);
      } else {
        console.error(response.error);
      }
    } else {
      const response = await collect(userId, post.interestId); // 执行收藏
      if (response.success) {
        setIsCollected(true);
      } else {
        console.error(response.error);
      }
    }
  };

   // 在组件渲染时设置初始收藏状态
   useEffect(() => {
    setIsCollected(post.isCollected); // 用于初始化收藏状态
  }, [post.isCollected]);

  // 添加评论或回复
  const handleSendComment = async(e) => {
    e.preventDefault();
    if (!commentText.trim()) return; // 空评论不发送
    
    try {
      await addComment(userId, post.blogId, commentText, repliedId);
      setCommentStates(repliedId ? { [repliedId]: false } : {}); // 被回复的评论的按钮重置
      setCommentText(''); // 清空输入框
      setReplyTo(null); // 清空回复目标
      setRepliedId(null); // 清空回复 ID
      setIsCommentInputActive(false); // 输入框失去焦点
      // 重新获取评论
      const updatedComments = await getCommentsByBlogId(post.blogId);
      setComments(updatedComments);// 更新状态
      setCommentsCount((prevCount) => prevCount + 1); // 更新评论数量
    } catch (err) {
      setError(err.message);
    }


      // 动画效果
      if (sendIconRef.current) {
        const icon = sendIconRef.current;
        icon.classList.remove("clicked");
        void icon.offsetWidth; // 强制重绘以触发动画
        icon.classList.add("clicked");
        setTimeout(() => {
          icon.classList.remove("clicked");
        }, 400);
      }

  };


  // 点击“回复”按钮
  const handleReply = (nickname, commentId) => {
    if(replyTo){
      setReplyTo(null);
      setRepliedId(null);
    }
    else{
      setReplyTo(nickname);
      setRepliedId(commentId);
    }
    setIsCommentInputActive(true);
    if (commentInputRef.current) commentInputRef.current.focus();
  };


  // 输入框激活状态
  const handleInputFocus = () => {
    setIsCommentInputActive(true);
  };
  
  // 点击文档处理函数
  const handleClickOutside = (event) => {
    if (commentInputRef.current && !commentInputRef.current.contains(event.target)) {
      setIsCommentInputActive(false); // 点击其他地方时恢复状态
    }
  }; 

  // 添加和清除事件监听器
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);


  const clickTopic = () => {
    if (!post.interestId) {
      console.error('Missing interestId');
      return;
    }
    navigate(`/topic/${post.interestId}`); // 确保传递正确的 interestId
  };
  

  // 点击头像跳转到用户详情页
  const UserDetails = () => {  
    navigate(`/personal/${post.userId}`); // 使用帖子中的 userId 跳转
  };

  const Details = () => {  
      navigate(`/post/${post.blogId}`);  // 你可以根据需要替换成具体的页面路径
  };



  const avatarSrc = post.userImage ? 'http://localhost:8080/'+ post.userImage : defaultAvatar;


  return (
    <div className="post">
      <div className="post-header">
        <img className="post-avatar" src={avatarSrc} alt="avatar" onClick={UserDetails}/>
        <div className="post-author-time">
          <span className="post-author-name">{post.author}</span>
          <span className="post-time">{formatDate(post.time)}</span>  {/* 使用格式化后的时间 */}
        </div>  
        {userId && post.userId && userId !== String(post.userId) && (
        <button 
          className={`follow-btn ${isFollowed ? 'followed' : 'not-followed'}`} 
          onClick={toggleFollow}
        >
          {isFollowed ? (
            <div className='follow-btn-inner-followed'>
              <span>已关注</span>
            </div>
          ) :( 
            <div className='follow-btn-inner-not-followed'>
              <span>关注</span>
            </div>
             
          )}
          {isFollowed ? (
            <FollowedIcon className="follow-icon" />
          ) : (
            <FollowIcon className="follow-icon" />
          )}
          
        </button>
        )}
      </div>
      <div className="post-body">
        <h3 onClick={clickTopic}># {post.title}</h3>
        <div className="post-content" style={{ 
          display: 'flex', 
          flexDirection: isDetailPage ? 'column' : 'row', 
        }}> 
        {post.blogImage && post.blogImage.length > 0 && (
          <div className="post-images">
          <img 
            src={'http://localhost:8080/' + post.blogImage} 
            alt="帖子图片" 
            style={{ width: isDetailPage ? '500px' : '170px' }} // 动态设置宽度
          />
        </div>
        )}

        <p>{post.content}</p> 
        </div>
      </div>
      <div className="post-footer">
        <div className="post-footer-item" onClick={toggleLike}>
           {isLiked ? (<img src={Loved} alt="Loved" className="post-footer-icon-img" />) : (<Love className="post-footer-icon" />)}
           <span className="post-footer-text">{likesCount || 0}</span> 
        </div>
        <div className="post-footer-item" onClick={toggleComment}>
          {isCommentedState ? (<img src={Commenting} alt="Commenting" className="post-footer-icon-img" />) : (<Comment className="post-footer-icon" />)}
          <span className="post-footer-text">{commentsCount || 0}</span>
        </div>
        <div className="post-footer-item" onClick={toggleCollect}>
          {isCollected ? (<img src={Collected} alt="Collected" className="post-footer-icon-img" />) : (<Collect className="post-footer-icon" />)}
        </div>
        {/* 判断是否显示 DetailIcon */}
        {!isDetailPage && (
          <div className="post-footer-item" style={{marginLeft: '30%'}} onClick={Details}>
            <DetailIcon className="post-footer-icon" />
          </div>
        )}
      </div>

      {isCommentedState && (
        <div className="comment-section">
          <div className={`comment-input ${isCommentInputActive ? "active" : ""}`} ref={commentInputRef}>
          <textarea
            value={commentText}
            onChange={(e) => setCommentText(e.target.value)}
            placeholder={replyTo ? `回复 ${replyTo}` : "写下你的评论..."}
            onFocus={handleInputFocus}
          />
          <button className="send-comment-btn" onClick={handleSendComment}>
            <SendIcon className="send-icon" ref={sendIconRef} />
          </button>
          </div>

           {/* 评论列表 */}
           <div 
            className="comments-list"
            style={{ 
              maxHeight: isDetailPage ? 'none' : '25vh', 
              overflowY: isDetailPage ? 'visible' : 'auto' 
            }}
          >
          {comments.length > 0
            ? comments.map((comment) => (
                <CommentItem
                  key={comment.commentId}
                  avatar={comment.userImage ? 'http://localhost:8080/' + comment.userImage : defaultAvatar}
                  nickname={comment.account}
                  time={new Date(comment.time).toLocaleString()}
                  text={comment.content}
                  repliedId={comment.repliedId}
                  replyTo={comment.repliedAccount}
                  onReply={() => handleReply(comment.account, comment.commentId)} // 传递用户 ID
                  isCommented={commentStates[comment.commentId] || false} // 传递当前评论的状态
                  setIsCommented={(state) => setCommentStates((prevStates) => ({
                  ...prevStates,
                  [comment.commentId]: state // 更新特定评论的状态
                }))} // 传递更新状态的函数
                />
              ))
            : "暂无评论"}
        </div>
        </div>
      )}
    </div>
  );
};

export default Post;
